package OrderQueue

import (
	"gdshop-back-end-go/client-api/app/request/OrderReq"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"github.com/gookit/event"
	jsoniter "github.com/json-iterator/go"
	"time"
)

// 本文件全部 为 SubmitOrder 队列

func AddSubmitOrder(submitData OrderReq.SubmitGroup) (string, error) {
	messageId := getMessageId()
	data, err := jsoniter.MarshalToString(submitData)
	if err != nil {
		return "", err
	}

	/*toString, err := jsoniter.MarshalToString(Message{
		ID:    messageId,
		Topic: "SubmitOrderQueue",
		Body:  data,
	})
	if err != nil {
		return "", err
	}
	_, err = g.Redis("queue").Do("PUBLISH", "SubmitOrderQueue", toString)
	if err != nil {
		return "", err
	}*/

	doSubmitOrderEventBus(&Message{
		ID:    messageId,
		Topic: "SubmitOrderQueue",
		Body:  data,
	})

	return messageId, nil
}

func initSubmitOrderQueue2() {
	conn := g.Redis("queue").Conn()
	_, err := conn.Do("SUBSCRIBE", "SubmitOrderQueue")
	if err != nil {
		panic(err)
	}
	var tmpMessage Message
	for {
		reply, err := conn.ReceiveVar()
		if err != nil {
			panic(err)
		}

		r := reply.Strings()
		err = gconv.Struct(r[2], &tmpMessage)
		if err != nil {
			panic(err)
		}

		doSubmitOrderEventBus(&tmpMessage)

		time.Sleep(500)
	}
}

// 通过 EventBus 方式解耦下单
func doSubmitOrderEventBus(m *Message) {
	err, _ := event.Trigger("SubmitQueue", map[string]interface{}{
		"Id":   m.ID,
		"Body": m.Body,
	})
	if err != nil {
		g.Log().Cat("doSubmitOrderEventBus").Async().Error("initSubmitOrderQueue2 11 失败", err.Error())
		return
	}
}
